package com.dyna.auth.controller;

import cn.hutool.core.util.StrUtil;
import com.dyna.api.domain.req.LoginEntity;
import com.dyna.api.domain.resp.AuthLoginResp;
import com.dyna.auth.service.LoginService;
import com.dyna.core.utils.SecurityUtil;
import com.dyna.domain.resp.R;
import com.dyna.enums.LoginLogTypeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.security.PermitAll;

@Api(value = "登录认证")
@RestController
@AllArgsConstructor
public class LoginController {

    private final LoginService loginService;

    @ApiOperation(value = "登录")
    @RequestMapping("/login")
    public R<AuthLoginResp> login(@RequestBody @Validated LoginEntity login) {
        return R.data(loginService.login(login));
    }

    @ApiOperation(value = "登出系统")
    @GetMapping("/logout")
    public R<Boolean> logout() {
        String token = SecurityUtil.getToken();
        if (StrUtil.isBlank(token)) {
            return R.data(false);
        }
        loginService.logout(token, LoginLogTypeEnum.LOGOUT_SELF.getType());
        return R.data(true);
    }

    @PostMapping("/refresh-token")
    @PermitAll
    @ApiOperation(value = "刷新令牌")
    @ApiImplicitParams(value = {@ApiImplicitParam(name = "refreshToken", value = "刷新令牌", required = true)})
    public R<AuthLoginResp> refreshToken(@RequestParam("refreshToken") String refreshToken) {
        return R.data(loginService.refreshToken(refreshToken));
    }

}
